package gsw.demo.pluggable.binder;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import gsw.demo.pluggable.R;
import gsw.demo.pluggable.TestAidl;

public class ActivityBinder extends AppCompatActivity {
    //远程服务的Binder对象
    TestAidl testAidl = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_binder);
        init();
    }

    private void init() {
        View.OnClickListener clickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (v.getId() == R.id.bindServer) {
                    bindRemoteServer();
                } else if (v.getId() == R.id.getBase) {
                    try {
                        String result = testAidl == null ? "请先连接服务！" : testAidl.getName();
                        Toast.makeText(ActivityBinder.this, result, Toast.LENGTH_SHORT).show();
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                } else if (v.getId() == R.id.getCustom) {
                    try {
                        Item1 item1 = new Item1("Tom", 1);
                        Item2 item2 = testAidl == null ? null : testAidl.getItem2(item1);
                        String result = testAidl == null ? "请先连接服务！" : item2.id + " : " + item2.name;
                        Toast.makeText(ActivityBinder.this, result, Toast.LENGTH_SHORT).show();
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        findViewById(R.id.bindServer).setOnClickListener(clickListener);
        findViewById(R.id.getBase).setOnClickListener(clickListener);
        findViewById(R.id.getCustom).setOnClickListener(clickListener);
    }

    /**
     * 绑定远程服务
     * action为"gsw.demopluggable2.binder.ServiceBinder"
     */
    private void bindRemoteServer() {
        Intent intent = new Intent();
        intent.setAction("gsw.demopluggable2.binder.ServiceBinder");
        intent.setPackage("gsw.toolpluggabledemo2");

        bindService(intent, new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
                testAidl = TestAidl.Stub.asInterface(iBinder);
            }

            @Override
            public void onServiceDisconnected(ComponentName componentName) {

            }
        }, Context.BIND_AUTO_CREATE);
    }
}
